package com.wuyou.sso.common.component;

import cn.hutool.core.map.MapUtil;
import com.wuyou.sso.common.contant.AuthConstants;
import com.wuyou.sso.common.contant.TokenInfoConstants;
import com.wuyou.sso.common.userDetails.CustomizedUser;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author lishangbu
 * @date 2019/09/17
 * <p>token增强，客户端模式不增强。
 */
@Component
@Primary
public class CustomizedTokenEnhancer implements TokenEnhancer {

    /**
     * Provides an opportunity for customization of an access token (e.g. through its additional
     * information map) during the process of creating a new token for use by a client.
     *
     * @param accessToken    the current access token with its expiration and refresh token
     * @param authentication the current authentication including client and user details
     * @return a new token enhanced with additional information
     */
    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (AuthConstants.CLIENT_CREDENTIALS.equals(
                authentication.getOAuth2Request().getGrantType())) {
            return accessToken;
        }

        final Map<String, Object> additionalInfo = MapUtil.newHashMap(6);
        CustomizedUser customizedUser = (CustomizedUser) authentication.getUserAuthentication().getPrincipal();
        additionalInfo.put(TokenInfoConstants.USER_ID, String.valueOf(customizedUser.getId()));
        additionalInfo.put(TokenInfoConstants.USER_NAME, customizedUser.getUsername());
        additionalInfo.put(TokenInfoConstants.DEPT_ID, String.valueOf(customizedUser.getDeptId()));
        additionalInfo.put(TokenInfoConstants.MOBILE, customizedUser.getMobile());
        additionalInfo.put(TokenInfoConstants.LICENSE, AuthConstants.PROJECT_LICENSE);
        additionalInfo.put(TokenInfoConstants.ACTIVE, Boolean.TRUE);
        additionalInfo.put(TokenInfoConstants.TENANT_ID, customizedUser.getTenantId().toString());
        additionalInfo.put(TokenInfoConstants.DISPLAY_NAME, customizedUser.getDisplayName());
        additionalInfo.put(TokenInfoConstants.COMPANY_CODE, customizedUser.getCompanyCode());
        additionalInfo.put(TokenInfoConstants.TENANT_NAME, customizedUser.getTenantName());
//        additionalInfo.put(TokenInfoConstants.TENANT_VO, customizedUser.getTenantVO());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}
